import React, { Component } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import LayoutFrame from 'src/layouts';
import LoadingComp from 'src/pages/fallback/LoadingComp';
import { BASE_NAME } from '../../config';
import loadRoutes from './routes';
import AuthRoute from './AuthRoute';

export default class AppRouter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userRoutes: []
    };
  }

  componentDidMount() {
    this.getUserRoutes();
  }

  getUserRoutes = async () => {
    const { remoteRoutes = [] } = this.props;
    await loadRoutes(remoteRoutes).then(userRoutes => {
      this.setState({
        userRoutes
      });
    });
  };

  render() {
    const { userRoutes } = this.state;
    const style = {
      display: 'flex', flexDirection: 'column', flex: 1, position: 'relative',
    };
    return userRoutes.length !== 0 ? (
      <BrowserRouter basename={BASE_NAME}>
        <div style={style}>
          <Route
            path="/"
            render={(props) => <LayoutFrame {...props} />}
          />
          <Switch>
            {userRoutes.map((item) => {
              const { path, component } = item;
              const isNoAuthRoute = false;
              return (
                <AuthRoute
                  key={path}
                  exact
                  path={path}
                  noAuth={isNoAuthRoute}
                  component={component}
                />
              );
            })}
            <Route component={() => (
              <div>Error</div>
            )}
            />
          </Switch>
        </div>
      </BrowserRouter>
    ) : <LoadingComp />;
  }
}
